package com.zd.sd;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zd.config.DeviceInfoConfig;
import com.zd.dao.ReceiverData;
import com.zd.mapper.ReceiverDataMapper;
import com.zd.utils.MqttUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;

@Component
@RequiredArgsConstructor
@Slf4j
public class DeviceTimeSend {

    private final ReceiverDataMapper receiverDataMapper;

    private final DeviceInfoConfig deviceInfoConfig;
    @Resource(name = "dataThreadPool")
    private ThreadPoolTaskExecutor executor;

    @Scheduled(cron = "0 0 * * * ?")
    public void sendDeviceTime() {
        // 定时任务的具体逻辑
        try {
            DynamicDataSourceContextHolder.push("sensorSource");
            Arrays.stream(deviceInfoConfig.getOneHourDevices().split(",")).forEach(sns -> {
                String[] strings = sns.split("-");
                String dataSn = strings[0];  //解算平台sn
                String sendSn = strings[1];  //设备sn
                String address = strings[2];  //设备485地址
                ReceiverData receiverData = receiverDataMapper.selectOne(new LambdaQueryWrapper<ReceiverData>().eq(ReceiverData::getSn, dataSn).orderByDesc(ReceiverData::getDatetime).last("limit 1"));
                if (ObjectUtil.isNotNull(receiverData)) {
                    byte[] dataBytes = receiverData.toLocationByteArray(Integer.parseInt(address));
                    executor.execute(() -> MqttUtil.SendDataByMqtt("tcp://124.71.85.152:1883", sendSn, "devicefrontparse", "devicefrontparse", sendSn + "/OTA", dataBytes));
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询失败", e);
        } finally {
            DynamicDataSourceContextHolder.poll();
        }
    }

}
